using UnityEngine;
using System.Collections;

[RequireComponent (typeof (Sprite))]
public class lwFader : MonoBehaviour {
	
	public delegate void EndFade();

	public Sprite m_pSprite;

	public bool m_bIsFading = false;
	
	void Awake () {
		m_pSprite = this.GetComponent<Sprite>();
		if ( m_pSprite	== null )
			Debug.LogWarning( "lwFader : No Sprite found !" );
	}

	public IEnumerator FadeInCoroutine(float duration, Color fadeColor, lwFader.EndFade callbackFadeEnd)
	{
		while(m_bIsFading)
			yield return null;
		m_bIsFading = true;
		m_pSprite.renderer.enabled = true;
		m_pSprite.SetColor(fadeColor);
		float fStartTime = Time.realtimeSinceStartup;
		float fTimeAccu = 0;
		while (fTimeAccu < duration)
		{
			m_pSprite.SetColor(new Color(fadeColor.r, fadeColor.g, fadeColor.b, 1 - (fTimeAccu / duration)));
			fTimeAccu = (Time.realtimeSinceStartup - fStartTime);
			yield return null;
		}

		m_pSprite.SetColor(new Color(fadeColor.r, fadeColor.g, fadeColor.b, 0));
		m_pSprite.renderer.enabled = false;

		if (callbackFadeEnd != null)
			callbackFadeEnd();

		m_bIsFading = false;
	}

	public IEnumerator FadeOutCoroutine(float duration, Color fadeColor, lwFader.EndFade callbackFadeEnd)
	{
		while(m_bIsFading)
			yield return null;
		m_bIsFading = true;
		m_pSprite.renderer.enabled = true;
		m_pSprite.SetColor(new Color(fadeColor.r, fadeColor.g, fadeColor.b, 0));
		float fStartTime = Time.realtimeSinceStartup;
		float fTimeAccu = 0;
		while (fTimeAccu < duration)
		{

			m_pSprite.SetColor(new Color(fadeColor.r, fadeColor.g, fadeColor.b, fTimeAccu / duration));
			fTimeAccu = (Time.realtimeSinceStartup - fStartTime);
			yield return null;
		}

		m_pSprite.SetColor(new Color(fadeColor.r, fadeColor.g, fadeColor.b, 1));

		if (callbackFadeEnd != null)
			callbackFadeEnd();

		m_bIsFading = false;
	}

	public void FadeIn(float duration, Color fadeColor, lwFader.EndFade callbackFadeEnd)
	{
		StartCoroutine(FadeInCoroutine(duration, fadeColor, callbackFadeEnd));
	}
	
	public void FadeOut(float duration, Color fadeColor, lwFader.EndFade callbackFadeEnd)
	{
		StartCoroutine(FadeOutCoroutine(duration, fadeColor, callbackFadeEnd));
	}
}
